import Taro, { Component } from '@tarojs/taro'
import {View, ScrollView, Text, Image} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import {AtActionSheet, AtActionSheetItem, AtButton, AtSearchBar} from 'taro-ui'
import { asyncLoadGroupbuy, setKeyword, reSetList } from '../../actions/groupBuy'
import './index.styl'
import { ListGoodItem } from "../../components/listGoodItem/index"

import withShare from '../../components/withShare'
import Poster from '../../components/poster/poster/poster'
import Poster2 from '../../components/poster/poster/posterfull'
import defaultShareImg from '../../assets/images/share.jpg';
import shareCodeImg from '../../assets/images/code.jpeg';
import cartImg from "../../assets/images/tabbar/tab-cart.png";
import pinImg from '../../assets/images/pin.png'
import shopImg from '../../assets/images/shop.png'


/**
 * TODO 1. 加上底部加载更多的提示
 */
@withShare({})
@connect(({ groupBuy, cart, shop, user }) => ({
  groupBuy, cart, shop, user
}), (dispatch) => ({
  // 加载社区拼购
  onAsyncGroup () {
    dispatch(asyncLoadGroupbuy())
  },
  // 设置关键词
  onSetKeyword (word) {
    dispatch(setKeyword(word))
  },
  // 搜索前准备
  onStartSearch () {
    dispatch(reSetList())
  }
}))
class Daily extends Component {
  constructor () {
    super(...arguments)
    this.state = {
      posterConfig : {
        width: 1000,
        height: 800,
        backgroundColor: '#fff',
        debug: false,
        images: [
          {
            url: defaultShareImg,
            width: 800,
            height: 800,
            y: 0,
            x: 100,
          }
        ]
      },
      posterConfig2: {
        width: 750,
        height: 1334,
        backgroundColor: '#fff',
        debug: false,
        texts: [
          // 名称
          {
            x: 750 / 2,
            y: 750 * 1.1,
            text: `社区生活家`,
            fontSize: Math.floor(750 * 0.06),
            color: '#555',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
          // 价格
          {
            x: 750 / 2,
            y: 750 * 1.17,
            text: `新鲜低价`,
            fontSize:  Math.floor(750 * 0.05),
            color: '#FD7474',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
          // 描述
          {
            x: 750 / 2,
            y: 750 * 1.24,
            text: `长按识别小程序二维码`,
            fontSize: Math.floor(750 * 0.04),
            color: '#B2B2B2',
            opacity: 1,
            zIndex: 9,
            textAlign: 'center',
            width: 650
          },
        ],
        images: [
          {
            url:  defaultShareImg,
            width: 750,
            height: 750,
            y: 0,
            x: 0,
          },
          {
            url: shareCodeImg,
            width: 750 * .4,
            height: 750 * .4,
            y: 750 * 1.3,
            x: Math.floor(750 * .3),
          }
        ]
      },
      shareActionSheetOpen: false, // 打开分享弹窗
      shareImg: defaultShareImg,
      posterImg: '',
      shareitem: {}
    }
  }
  config = {
    navigationBarTitleText: '社区拼购',
    onReachBottomDistance: 300,
    usingComponents: {
      'poster': '../../components/poster/poster/index',
    }
  }

  // 设置搜索关键词
  onSearchValueChange (value) {
    this.props.onSetKeyword(value)
  }

  // 点击搜索
  onSearchActionClick () {
    this.props.onStartSearch()
    this.props.onAsyncGroup() // 加载社区拼购
  }

  // 设置分享标题
  $setShareTitle = () => {
    const {  name, spec_name, weight } = this.state.shareitem
    return spec_name ? `${name}` : `${name}`
  }

  // 设置分享图
  $setShareImageUrl = () => {
    const {  shareImg } = this.state
    return shareImg
  }

  // 页面到达底部
  onReachBottom () {
    const {nomore} = this.props.groupBuy
    if (nomore) return
    this.props.onAsyncGroup() // 加载社区拼购
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
    this.props.onSetKeyword('')
    this.props.onStartSearch() // 重置
    this.props.onAsyncGroup() // 加载社区拼购
  }

  // 点击封面
  onThumbClick (shareitem, e) {
    console.log('点击封面')
    console.log(e)
    e.preventDefault()
    e.stopPropagation()
    const  {thumb, origin_price, price,weight,spec_name} = shareitem
    this.setState({
      shareitem,
      posterConfig: {
        width: 1000,
        height: 800,
        backgroundColor: '#fff',
        debug: false,
        blocks: [
          {
            x: 0,
            y: 600,
            width: 1000, // 如果内部有文字，由文字宽度和内边距决定
            height: 200,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 40,
            zIndex: 1,
          },
          {
            x: 0,
            y: 760,
            width: 40,
            height: 40,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 0
          },
          {
            x: 960,
            y: 760,
            width: 40,
            height: 40,
            paddingLeft: 0,
            paddingRight: 0,
            borderWidth: 0,
            backgroundColor: '#FFC93E',
            borderRadius: 0
          }
        ],
        texts: [
          {
            x: 50,
            y: 660,
            text: [
              {
                text: `¥ ${parseFloat(price / 100).toFixed(2)}`,
                fontSize: 80,
                color: 'white',
                opacity: 1,
                marginLeft: 0,
                marginRight: 40,
                lineHeight: 140,
                lineNum: 1,
              },
              /*{
                text: `原价¥ ${parseFloat(origin_price / 100).toFixed(2)}`,
                fontSize: 50,
                color: 'white',
                opacity: 1,
                marginLeft: 10,
                textDecoration: 'line-through',
              },*/
            ],
            zIndex: 9,
            baseLine: 'middle',
          },
          {
            x: 50,
            y: 740,
            text: `${weight}g/${spec_name}`,
            fontSize: 50,
            color: 'white',
            opacity: 1,
            baseLine: 'middle',
            zIndex: 9,
          },
        ],
        images: [
          {
            url: thumb || defaultShareImg,
            width: 800,
            height: 800,
            y: 0,
            x: 100,
          }
        ]
      }
    })
    setTimeout(() => {
      Poster.create(true)    // 入参：true为抹掉重新生成
    }, 200)
    Taro.showLoading({})

  }

  onPosterSuccess (preview, e) {
    const { detail } = e;
    Taro.hideLoading()
    // 预览
    if (preview === 'poster') {
      console.log('生成海报成功')
      this.setState({
        posterImg: detail,
        shareActionSheetOpen: false
      })
      Taro.previewImage({
        current: detail,
        urls: [detail]
      })
    }
    // 分享
    if (preview === 'share') {
      console.log('生成分享图成功')
      this.setState({
        shareImg: detail,
        shareActionSheetOpen: true
      })
    }
  }

  onPosterFail () {
    console.log('失败')
    Taro.hideLoading()
  }

  handleActionSheetOpen () {
    this.setState({
      shareActionSheetOpen: true
    })
  }

  // 分享actionsheet 关闭
  handleActionSheetClose () {
    this.setState({
      shareActionSheetOpen: false
    })
  }

  // 分享actionsheet 取消
  handleActionSheetCancel () {
    this.setState({
      shareActionSheetOpen: false,
      shareImg: defaultShareImg
    })
  }

  // 分享actionsheet 点击
  handleActionSheetClick (type) {
    this.setState({
      shareActionSheetOpen: false
    })
    if (type === 'poster') {
      const { name, spec_name, thumb, price, weight } = this.state.shareitem
      const {avatar, nickname} = this.props.user
      const {name: shopname, address = '店家未设置'} = this.props.shop

      Taro.getSystemInfo({}).then(({screenWidth, screenHeight, pixelRatio}) => {
        const width = screenWidth * pixelRatio
        const height = Math.max(screenHeight * pixelRatio, Math.floor(width * 1.8))
        const codeWidth = Math.floor(width * .4)
        this.setState({
         // 列表分享
          posterConfig2: {
            width,
            height:height - 50,
            backgroundColor: '#000',
            debug: false,
            texts: [
              // 名称
              {
                x: width / 2,
                y: width * 1.1,
                text: `${name}`,
                fontSize: Math.floor(width * 0.06),
                color: '#555',
                opacity: 1,
                zIndex: 9,
                textAlign: 'center',
                width: width - 100
              },
              // 价格
              {
                x: width / 2,
                y: width * 1.17,
                text: [
                  {
                    text: `¥ ${parseFloat(price / 100).toFixed(2)}`,
                    fontSize:  Math.floor(width * 0.05),
                    color: '#FD7474',
                    textAlign: 'center',
                  }
                ]
              },
              // 规格
              {
                x: width / 2,
                y: width * 1.24,
                text: [
                  {
                    text: `${weight}g/${spec_name}`,
                    fontSize: Math.floor(width * 0.04),
                    color: '#B2B2B2',
                    marginLeft: 30,
                    textAlign: 'center',
                  }
                ]
              },
              // 描述
              {
                x: width / 2,
                y: width * 1.30,
                text: `长按识别小程序二维码3`,
                fontSize: Math.floor(width * 0.04),
                color: '#B2B2B2',
                opacity: 1,
                zIndex: 9,
                textAlign: 'center',
                width: width - 100
              },
            ],
            images: [
              {
                url: thumb || defaultShareImg,
                width,
                height: width,
                y: 0,
                x: 0,
              },
              {
                url: shareCodeImg,
                width: codeWidth,
                height: codeWidth,
                y: width * 1.4,
                x: Math.floor(width * .3),
              }
            ]
          }
        })
        setTimeout(() => {
          Poster2.create(true)    // 入参：true为抹掉重新生成
        }, 200)
      })
    }
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }
  componentDidMount () {
    this.props.onSetKeyword('')
    this.props.onStartSearch() // 重置
    this.props.onAsyncGroup() // 加载社区拼购
  }
  componentWillUnmount () { }

  componentDidShow () {}

  componentDidHide () { }

  render () {
    const { list, search } = this.props.groupBuy
    const { posterConfig, posterConfig2, shareActionSheetOpen } = this.state
    const {cart_num} = this.props.cart

    const renderGroupList = list.map((item, index) => {
      return (
        <ListGoodItem
          key={index}
          goodId={item.id}
          tags={item.tags}
          thumb={item.thumb}
          name={item.name}
          star={item.point}
          offer={item.offer}
          price={item.sale_price}
          sale_price={item.sale_price}
          original_price={item.original_price}
          spec_name={item.spec.name}
          weight={item.weight}
          //onThumbClick={this.onThumbClick.bind(this)}
          isGroup
        />
      )
    })
    return (
      <View className='daily'>
        <AtSearchBar
          fixed
          value={search}
          onChange={this.onSearchValueChange.bind(this)}
          onActionClick={this.onSearchActionClick.bind(this)}
        />
         {/* <View className='discount'>满36减6 满54减9 </View> */}
        <ScrollView
          className='daily-list'
          enableBackToTop
          scrollY
          scrollWithAnimation
          scrollTop='0'
        >
          {renderGroupList}
        </ScrollView>

        {/*海报生成器*/}
        <poster
          id='poster'
          config={posterConfig}
          onSuccess={this.onPosterSuccess.bind(this, 'share')}
          onFail={this.onPosterFail.bind(this)}
        />

        {/*全屏海报生成器*/}
        <poster
          id='poster2'
          config={posterConfig2}
          onSuccess={this.onPosterSuccess.bind(this, 'poster')}
          onFail={this.onPosterFail.bind(this)}
        />
        {/*actionsheet*/}
        <AtActionSheet
          isOpened={shareActionSheetOpen}
          cancelText='取消'
          onCancel={this.handleActionSheetCancel.bind(this)}
          onClose={this.handleActionSheetClose.bind(this)}
        >
          <AtActionSheetItem onClick={this.handleActionSheetClick.bind(this, 'share')}>
            <AtButton openType='share' className='share-action-btn'>
              <Text className='text'>分享</Text>
            </AtButton>
          </AtActionSheetItem>
          <AtActionSheetItem onClick={this.handleActionSheetClick.bind(this, 'poster')}>
            <AtButton className='share-action-btn'>
              <Text className='text'>生成卡片保存分享</Text>
            </AtButton>
          </AtActionSheetItem>
        </AtActionSheet>

        {/*购物车图标*/}


      </View>
    )
  }
}

export default Daily
